//! tracing日志相关
use time::{macros::format_description, UtcOffset};
use tracing_subscriber::fmt::time::OffsetTime;
use tracing_subscriber::EnvFilter;

/// 初始化tracing日志框架
///
/// 使用方法：
/// ```
/// use wang_utils_logger::tracing::init_tracing;
///
/// use tracing::info;
/// use tracing::debug;
///
/// fn main() {
///     // 设置日志级别，默认为ERROR
///     std::env::set_var("RUST_LOG", "info");
///     // 测试logger包
///     init_tracing();
///     info!("这是info级别的日志");
///     debug!("这是debug级别的日志");
/// }
/// ```
pub fn init_tracing() {
    let local_time = OffsetTime::new(
        UtcOffset::from_hms(8, 0, 0).unwrap(),
        format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"),
    );
    tracing_subscriber::fmt()
        //使用环境变量动态加载日志级别，默认为ERROR
        //RUST_LOG=info cargo run
        .with_env_filter(EnvFilter::from_default_env())
        .with_timer(local_time)
        .init();
}

#[cfg(test)]
/// 单元测试时初始化tracing，级别设置为DEBUG
pub fn init_test_tracing() {
    use std::env;
    env::set_var("RUST_LOG", "DEBUG");
    init_tracing();
}

#[cfg(test)]
mod tests {
    use super::*;
    use tracing::{debug, info};

    #[test]
    fn test1() {
        init_test_tracing();
        info!("info hello");
        debug!("debug hello");
    }
}
